// router/index.js
import { createWebHistory, createRouter } from 'vue-router';
import Login from '@/views/Login.vue';
import Home from '@/views/Home.vue';
import Welcome from '@/views/Welcome.vue';
import store from '@/store/index.js';

const routes = [
  { path: '/', redirect: '/login' },
  { path: '/login', component: Login },
  {
    path: '/home',
    component: Home,
    name: 'Home',
    redirect: '/welcome',
    children: [
      {
        path: '/welcome',
        component: Welcome
      },
    ]
  }
  // 404路由将在动态路由加载后再添加
]

const router = createRouter({
  history: createWebHistory(),
  routes,
})

// 修改路由转换函数
const createRouteFromRouters = (routers) => {
  // 预加载所有组件
  const viewModules = import.meta.glob('@/views/**/Index.vue');
  
  return routers.map(route => {
    // 去掉开头的斜杠
    const routePath = route.startsWith('/') ? route.substring(1) : route;
    // 构建组件路径
    const componentPath = `/src/views/${routePath}/Index.vue`;
    
    return {
      path: route,
      component: () => {
        if (viewModules[componentPath]) {
          return viewModules[componentPath]();
        } else {
          console.error(`路径不存在: ${componentPath}`);
          return import('@/views/error/404.vue');
        }
      }
    };
  });
};


// 标记是否已添加404路由
let is404Added = false;

router.beforeEach(async (to, from, next) => {
  // 登录页面直接通过
  console.log("to",to.path)
  if (to.path === '/login') {
    return next();
  }
  
  // 判断是否需要加载路由
  if (localStorage.getItem("routers") === undefined || localStorage.getItem("routers") === null) {
    try {
      await store.dispatch('getHome');
      
      // 转换并添加动态路由
      const dynamicRoutes = createRouteFromRouters(store.state.routers);
      let hasAddedRoutes = false;
      
      if (dynamicRoutes.length > 0) {
        dynamicRoutes.forEach(route => {
          const existingRoute = router.getRoutes().find(r => r.path === route.path);
          if (!existingRoute) {
            router.addRoute('Home', route);
            hasAddedRoutes = true;
          }
        });
      }
      
      // 添加404路由（确保它在所有路由之后）
      if (!is404Added) {
        router.addRoute({
          name: '404',
          path: '/:catchAll(.*)',
          component: () => import('@/views/error/404.vue')
        });
        is404Added = true;
      }
      
      // 如果添加了新路由，需要重新导航到目标页面
      if (hasAddedRoutes) {
        // 使用replace模式重定向，避免在历史记录中留下重复记录
        return next({ path: to.fullPath, replace: true });
      }
    } catch (error) {
      console.error('加载路由失败:', error);
      return next('/login');
    }
  }
  
  next();
});

export default router
